<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class Product extends Model
{
    protected $fillable = [
        'title',
        'description',
        'image',
        'on_sale'
    ];

    const IS_SALE = true;
    const NOT_SALE = false;

    public static $saleMap = [
        self::IS_SALE => '是',
        self::NOT_SALE => '否'
    ];

    const TYPE_PENDING = 'pending';
    const TYPE_BIDDING = 'bidding';
    const TYPE_ADMIN_RECYCLE = 'admin_recycle';
    const TYPE_SUCCESS = 'success';
    const TYPE_NO_BIDDERS = 'no_bidders';

    public static $typeMap = [
        self::TYPE_PENDING => '等待竞拍',
        self::TYPE_BIDDING => '竞拍中',
        self::TYPE_ADMIN_RECYCLE => '商品管理员回收',
        self::TYPE_SUCCESS => '商品竞拍成功',
        self::TYPE_NO_BIDDERS => '没有竞标者'
    ];

    protected $casts = [
        'on_sale' => 'boolean',  // on_sale 是一个布尔类型的字段
        'start_at' => 'dateTime',
        'end_at' => 'dateTime'
    ];

    // 生成图片绝对路径
    public function getImageUrlAttribute()
    {
        if (Str::startsWith($this->attributes['image'], ['http://', 'https://'])) {
            return $this->attributes['image'];
        }
        return Storage::disk('public')->url($this->attributes['image']);
    }

    // 商品竞价关联参与竞价用户
    public function bidder()
    {
        return $this->belongsToMany(User::class, 'product_bids')
            ->withPivot(['money', 'now_price'])
            ->withTimestamps()
            ->orderBy('created_at', 'desc');
    }

    // 商品竞价列表
    public function biddingList()
    {
        return $this->hasMany(ProductBid::class);
    }

    // 成交用户
    public function auctionWinner()
    {
        return $this->hasOne(AuctionWinner::class);
    }
}
